package generalClasses;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import LeaderElection.RetreiveIPs;

public class PingMachine
{
	/**
	 * @author Sapir
	 */
//	private final static
	
	private String _ipconfigCommand = "ipconfig";
	private String _pingCommand = "ping";
	private final String _defaultGateway = "Default Gateway";
	private final String _SEMICOLON = "::";
	
	private final String _BYTES = "bytes";
	private final String _TIME = "time";
	private final String _TTL = "TTL";
	
	public ProgramData _pd;
	
	
	public PingMachine()
	{
		super();
		_pd = new ProgramData();
	}
	/**
	 * Find the IP address of default gateway
	 * @return {@link String} - IP address of default gateway
	 * @author Sapir
	 */
	private String findGateway()
	{
		String gatewayAddress = null;
		try
		{
			//generate "ipconfig" command
			Process netstatExecCommand = Runtime.getRuntime().exec( _ipconfigCommand );
			//generate BufferedReader for the command output
			BufferedReader output = new BufferedReader(new InputStreamReader( netstatExecCommand.getInputStream() ));
			String cmdLine = output.readLine();
			//netstatExecCommand still has output
			while(cmdLine != null)
			{
//				System.out.println( cmdLine );
				//we have reached "Default Gateway" in netstatExecCommand output
				if ( cmdLine.contains( _defaultGateway ) == true && cmdLine.endsWith( _SEMICOLON ) == false)
				{
					break;              
				}
				cmdLine = output.readLine();
			}
			if ( cmdLine != null )
			{
				int indexOfSemicolon = cmdLine.indexOf(":");
				gatewayAddress = cmdLine.substring( indexOfSemicolon + 1 );
			}
		}
		catch( IOException e ) 
		{ 
			System.out.println( e.toString() );
		}
		return gatewayAddress;
	}
	/**
	 * Ping a given address\IP address
	 * @param destinationAddress - address\IP address to ping to  
	 * @return true - if all 4 pings to destinationAddress were successful.<br>
	 * false - if at least one of the 4 pings to destinationAddress wan't not successful
	 * @author Sapir
	 */
	private boolean pingAddress(String destinationAddress )
	{
		boolean result = false;
		if ( destinationAddress != null)
		{
			try
			{
				//generate "ping" command
				Process pingExecCommand = Runtime.getRuntime().exec( _pingCommand + " " + destinationAddress );
				//generate BufferedReader for the command output
				BufferedReader output = new BufferedReader(new InputStreamReader( pingExecCommand.getInputStream() ));
				String cmdLine = output.readLine();

				int successCounter = 0;
				
				while(cmdLine != null)
				{
//					System.out.println( cmdLine );
					if ( ( cmdLine.contains(_BYTES) ) && ( cmdLine.contains(_TIME) ) && ( cmdLine.contains(_TTL) ) )
					{
						successCounter++;
					}
					//we have reached "Default Gateway" in netstatExecCommand output
					cmdLine = output.readLine();
				}
				//all pingExecCommand outputs were reply from default gateway 
				if ( successCounter >= 4 )
				{
					result = true;
				}
			}
			catch( IOException e ) 
			{ 
				System.out.println( e.toString() );
			}
		}
		return result;
	}
	
	/**
	 * Check that communication with default Gateway works OK
	 * @return true - if all 4 ping commands to default Gateway were successful.<br>
	 *  false - if one of the 4 ping commands to default Gateway wan't successful.<br>
	 *  
	 *  *each 4 ping commands are one execution of Ping in Windows Command Prompt
	 * @author Sapir
	 */
	public static boolean callGateway()
	{
		PingMachine pingGateway = new PingMachine();
		//find gateway
		String defaultGatewayAddress = pingGateway.findGateway();
		//ping gateway and return result
		boolean isDefaultGatewayUp = pingGateway.pingAddress( defaultGatewayAddress );
		
		return isDefaultGatewayUp;
	}
	/**
	 * Check that communication with BackupServer works OK
	 * @return true - if all 4 ping commands to BackupServer were successful.<br>
	 *  false - if one of the 4 ping commands to BackupServer wan't successful.
	 *  
	 *  
	 *  *each 4 ping commands are one execution of Ping in Windows Command Prompt
	 * @author Sapir
	 */
	public static boolean callBackup()
	{
		PingMachine pingGateway = new PingMachine();
		//find Backup Server Name
		String backupServerName = pingGateway._pd.getBackupServerAdress();
		//find Backup Server IP Address
		String backupServerIPAddress = RetreiveIPs.findIPaddress( backupServerName );
		//ping BackupServer and return result
		boolean isBackupServerUp = pingGateway.pingAddress( backupServerIPAddress );
		
		return isBackupServerUp;
	}
	/**
	 * Check that communication with MainServer works OK
	 * @return true - if all 4 ping commands to MainServer were successful.<br>
	 *  false - if one of the 4 ping commands to MainServer wan't successful.
	 *  
	 *  
	 *  *each 4 ping commands are one execution of Ping in Windows Command Prompt
	 * @author Sapir
	 */
	public static boolean callMain()
	{
		PingMachine pingGateway = new PingMachine();
		//find Main Server Name 
		String mainServerName = pingGateway._pd.getMainServerAdress(); 
		//find Main Server IP Address
		String mainServerIPAddress = RetreiveIPs.findIPaddress( mainServerName );
		//ping BackupServer and return result
		boolean isMainServerUp = pingGateway.pingAddress( mainServerIPAddress );
		
		return isMainServerUp;
	}

	public static void main(String args[])
	{
//		System.out.println("Answer of callBackup() is: " + callBackup() );
//		System.out.println("Answer of callMain() is: " + callMain() );
		System.out.println("Answer of callGateway() is: " + callGateway() );
	}
}

